package ${package.Stereotype}.security.authentication;

import com.fasterxml.jackson.databind.ObjectMapper;
import ${package.Stereotype}.security.bean.AbstractUser;
import ${package.Stereotype}.security.bean.LoginUser;
import ${package.Stereotype}.security.impl.CacheServiceImpl;
import ${package.Stereotype}.security.impl.LoginAttemptService;
import ${package.Stereotype}.util.JwtUtil;
import ${package.Stereotype}.vo.ResultVo;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.UUID;

/**
 * 认证登录成功处理
 */
@Component
public class AuthenticationSuccess implements AuthenticationSuccessHandler {

    @Resource
    private LoginAttemptService attempt;

    @Resource
    private CacheServiceImpl cacheService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        ObjectMapper mapper = new ObjectMapper();
        ResultVo responseEntity = new ResultVo((Object)null);
        response.setHeader("Content-Type", "application/json;charset=UTF-8");
        String username = httpServletRequest.getParameter("username");
        attempt.loginSuccessed(username);
        if (authentication != null) {
            LoginUser userToken = new LoginUser();
            userToken.setTokenId(UUID.randomUUID().toString().replaceAll("-", ""));
            AbstractUser user = (AbstractUser) authentication.getPrincipal();
            String token = JwtUtil.sign(user.getSecurityUsername(), user.getSecurityPassword(), userToken.getTokenId());
<#assign String = 'String' />
<#assign Object = 'Object' />
            HashMap<${String}, ${Object}> map = new HashMap<>();
            map.put("username", user.getSecurityUsername());
            map.put("permission", authentication.getAuthorities());
            map.put("token", token);
            responseEntity.setCode(HttpStatus.OK.value());
            responseEntity.setMsg("登录成功");
            responseEntity.setData(map);
            response.setStatus(HttpStatus.OK.value());
            //用户token信息录入
            userToken.setUserName(user.getSecurityUsername());
            userToken.setPwd(user.getSecurityPassword());
            userToken.setRoleIds(user.getSecurityRole());
            userToken.setToken(token);
            //将token 序列化到缓存中
            cacheService.setLoginUser(userToken);
            response.getWriter().write(mapper.writeValueAsString(responseEntity));
        }
    }
}
